package hz.mobileproject.pda.ui.activity.work;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.czt.mp3recorder.MP3Recorder;
import com.google.gson.Gson;
import com.google.zxing.activity.CaptureActivity;
import com.shuyu.waveview.AudioPlayer;
import com.shuyu.waveview.AudioWaveView;
import com.shuyu.waveview.FileUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.broadcast.HandleBroadcast;
import hz.mobileproject.pda.broadcast.IShowBarcodeStr;
import hz.mobileproject.pda.db.DBManager;
import hz.mobileproject.pda.entity.request.Request_Edu_inter;
import hz.mobileproject.pda.entity.request.Request_loadPersioneInfo;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Rp_eduType;
import hz.mobileproject.pda.entity.response.Rp_eduTypeArrList;
import hz.mobileproject.pda.entity.response.Rp_loadPrisonerInfo;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.ui.adapter.EduUploadPopAdapter;
import hz.mobileproject.pda.ui.base.BaseActivity;
import hz.mobileproject.pda.ui.view.CustomPopWindow;
import hz.mobileproject.pda.ui.view.LoadingDialog;
import hz.mobileproject.pda.utils.CommonUtil;
import hz.mobileproject.pda.utils.HttpRqUtils;

@ContentView(R.layout.activity_edu_upload)
public class EduUploadActivity extends BaseActivity implements IShowBarcodeStr {
    @ViewInject(R.id.tv_policeName)
    private TextView tv_policeName;
    @ViewInject(R.id.tv_prisonerName)
    private TextView tv_prisonerName;
    @ViewInject(R.id.tv_policeID)
    private TextView tv_policeID;
    @ViewInject(R.id.tv_prisonerID)
    private TextView tv_prisonerID;
    @ViewInject(R.id.tv_policeDept)
    private TextView tv_policeDept;
    @ViewInject(R.id.tv_prisonerDept)
    private TextView tv_prisonerDept;
    @ViewInject(R.id.tv_tanhua_leixing)
    private TextView tv_tanhua_leixing;
    @ViewInject(R.id.tv_tanhua_content)
    private TextView tv_tanhua_content;
    @ViewInject(R.id.timer)
    private Chronometer timer;
    @ViewInject(R.id.audioWave)
    private AudioWaveView audioWave;
    @ViewInject(R.id.btn_startRecord)
    private Button btn_startRecord;
    @ViewInject(R.id.btn_recordPause)
    private Button btn_recordPause;
    @ViewInject(R.id.btn_recordStop)
    private Button btn_recordStop;
    @ViewInject(R.id.btn_ReRecord)
    private Button btn_ReRecord;
    @ViewInject(R.id.btn_play)
    private Button btn_play;
    @ViewInject(R.id.btn_playPause)
    private Button btn_playPause;
    @ViewInject(R.id.btn_playStop)
    private Button btn_playStop;
    @ViewInject(R.id.btn_submit)
    private Button btn_submit;

    private Gson mGson;
    public DBManager dBManager;
    //谈话配置
    private Rp_eduTypeArrList mEduTypeArrList;
    //当前选中 - 谈话类型
    private Rp_eduType mSelectedTalkClassify;
    //当前选中 - 谈话类型子项
    private Rp_eduType mSelectedTalkClassifySon;
    //当前扫码民警
    private Response_loadPoliceInfo mPolice;
    //当前扫码罪犯
    private Rp_loadPrisonerInfo mPrisoner;

    /**upd
     * 扫码相关---------------------------
     */
    private HandleBroadcast mHandleBroadcast;
    private SoundPool mSoundpool;
    private LoadingDialog mLoadingDialog;
    //红外扫描音效id
    private int mSoundid;
    //扫描成功返回码
    private static final int SCAN_RESULT_OK = 0xA1;
    private static final int REQUEST_CODE_POLICE = 0x1011;
    private static final int REQUEST_CODE_PRISONER = 0x1012;

    /**
     * 录音与播放相关-------------------------
     */
    //当前录音文件存储路径
    private String mFilePath;
    private MP3Recorder mRecorder;
    boolean mIsRecord = false;
    private long mTimerNum = 0l;
    private AudioPlayer mAudioPlayer;
    private boolean mIsPlay;
    private int curPosition;
    private int duration;

    @Override
    protected void initData() {
        mGson = new Gson();
        dBManager = DBManager.getInstance(getApplicationContext());
        mAudioPlayer = new AudioPlayer(this, mHandler);
        mLoadingDialog = new LoadingDialog(this);
        //防止空指针先实例化
        mEduTypeArrList = new Rp_eduTypeArrList();
        //接口获取谈话配置
        getTalkType();
        //打开红外扫码  扫描民警
        openScan(REQUEST_CODE_POLICE);
    }


    @Event({R.id.tv_policeName, R.id.tv_prisonerName, R.id.tv_tanhua_leixing,
            R.id.tv_tanhua_content, R.id.btn_startRecord, R.id.btn_recordPause,
            R.id.btn_recordStop, R.id.btn_ReRecord, R.id.btn_submit, R.id.btn_play,
            R.id.btn_playPause, R.id.btn_playStop})
    private void viewOnClick(View v) {
        switch (v.getId()) {
            case R.id.tv_policeName://点击扫描民警条码
                openScan(REQUEST_CODE_POLICE);
                break;
            case R.id.tv_prisonerName://点击扫描罪犯条码
                openScan(REQUEST_CODE_PRISONER);
                break;
            case R.id.tv_tanhua_leixing://点击谈话类型
                showPopWindow(mEduTypeArrList.getTalk_classify(), tv_tanhua_leixing);
                break;
            case R.id.tv_tanhua_content://点击谈话类型子项
                if (mSelectedTalkClassify == null) {
                    ToastUtils.showLong("请先选择谈话类型");
                    return;
                }
                showPopWindow(mSelectedTalkClassify.getSub_data(), tv_tanhua_content);
                break;
            case R.id.btn_startRecord://开始录音
                resolveRecord();
                break;
            case R.id.btn_recordPause://暂停录音
                resolvePause();
                break;
            case R.id.btn_recordStop://停止录音
                resolveStopRecord();
                timer.stop();
                break;
            case R.id.btn_ReRecord://重新录音
                resolveReRecord();
                break;
            case R.id.btn_play://播放录音
                resolvePlayRecord();
                break;
            case R.id.btn_playPause://暂停播放
                resolvePausePlay();
                break;
            case R.id.btn_playStop://停止播放
                mAudioPlayer.stop();
                resolveStopUI();
                break;
            case R.id.btn_submit://下一页
                startToEvaluate();
                break;
        }
    }

    /**
     * 打开扫描
     */
    private void openScan(int requestCode) {
        if (Constance.isNeiMeng) {  //如果是演示版本则打开相机扫描
            //打开二维码扫描界面
            if (CommonUtil.isCameraCanUse()) {
                Intent intent = new Intent(this, CaptureActivity.class);
                startActivityForResult(intent, requestCode);
            } else {
                Toast.makeText(this, "请打开此应用的摄像头权限！", Toast.LENGTH_SHORT).show();
            }
        } else {
            mHandleBroadcast = new HandleBroadcast(this, this);
            mSoundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
            mSoundid = mSoundpool.load("/etc/Scan_new.ogg", 1);
            if (requestCode == REQUEST_CODE_POLICE) {
                mLoadingDialog.setTag(REQUEST_CODE_POLICE);
                mLoadingDialog.setMessage("请扫描民警二维码").show();
            } else if (requestCode == REQUEST_CODE_PRISONER) {
                mLoadingDialog.setTag(REQUEST_CODE_PRISONER);
                mLoadingDialog.setMessage("请扫描罪犯二维码").show();
            }
        }
    }


    /**
     * 红外扫码回调
     *
     * @param msg
     */
    @Override
    public void updateText(String msg) {
        if (!mLoadingDialog.isShowing()) {
            return;
        }
        mSoundpool.play(mSoundid, 1, 1, 0, 0, 1);
        if (mLoadingDialog.getTag() == REQUEST_CODE_POLICE) {
            //兼容四监条码，不含P
            //获取民警信息
            getPliceInfoFromSer(msg);
        } else if (mLoadingDialog.getTag() == REQUEST_CODE_PRISONER) {
            //获取罪犯信息
            getPrisonerInfoFromSer(msg);
        }
    }

    /**
     * 摄像头扫码回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != SCAN_RESULT_OK) {
            return;
        }
        //扫描结果回调
        Bundle bundle = data.getExtras();
        String scanStr = bundle.getString("qr_scan_result");
        if (requestCode == REQUEST_CODE_POLICE) {
            //获取民警信息
            getPliceInfoFromSer(scanStr);
        } else if (requestCode == REQUEST_CODE_PRISONER) {
            //获取罪犯信息
            getPrisonerInfoFromSer(scanStr);
        }
    }


    /**
     * 请求网络接口获取谈话配置
     */
    private void getTalkType() {
        HttpRqUtils.httpGet(Constance.BASE_URL + Constance.URL_EDUTALK_LOAD_TYPE, talkTypeCallBack);
    }

    /**
     * 获取谈话配置接口回调
     */
    private CustomNetCallBack talkTypeCallBack = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            mEduTypeArrList = mGson.fromJson(data, Rp_eduTypeArrList.class);
            if (mEduTypeArrList == null) {
                ToastUtils.showLong("谈话配置为空");
                return;
            }
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取谈话配置失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取谈话配置失败");
            LogUtils.e(ex);
        }
    };


    /**
     * 请求网络接口获取民警信息
     *
     * @param scanStr
     */
    private void getPliceInfoFromSer(String scanStr) {
//        if (scanStr.indexOf("P") != 0) {
//            ToastUtils.showLong("条码格式错误，请确认为民警条码");
//            return;
//        }
//        scanStr = scanStr.substring(scanStr.indexOf("P") + 1);
        scanStr = scanStr.contains("P") ? scanStr.substring(1): scanStr;
        Request_loadPoliceInfo rq_lpi = new Request_loadPoliceInfo();
        rq_lpi.setCusNumber(SPUtils.getInstance("app_login").getString(Constance.SP_CUSNUMBER));
        rq_lpi.setPoliceCode(scanStr);
        //发送获取民警信息接口请求
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_POLICE_INFO, rq_lpi, policeInfoCallback);
    }

    /**
     * 获取民警信息接口回调
     */
    private CustomNetCallBack policeInfoCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            Response_loadPoliceInfo loadPoliceInfo = mGson.fromJson(data, Response_loadPoliceInfo.class);
            if (loadPoliceInfo == null) {
                ToastUtils.showLong("民警信息为空");
                return;
            }
            tv_policeName.setText(loadPoliceInfo.getPolice_name());
            tv_policeID.setText(loadPoliceInfo.getPolice_code());
            tv_policeDept.setText(loadPoliceInfo.getDepartment_name());
            mPolice = loadPoliceInfo;

            //打开扫描罪犯
            mLoadingDialog.dismiss();
            openScan(REQUEST_CODE_PRISONER);

        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取民警信息失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取民警信息失败");
            LogUtils.e(ex);
        }
    };


    /**
     * 请求网络接口获取罪犯信息
     *
     * @param scanStr
     */
    private void getPrisonerInfoFromSer(String scanStr) {
        scanStr = scanStr.substring(scanStr.indexOf("P") + 1);
        LogUtils.e(scanStr);
        Request_loadPersioneInfo rq_lpi = new Request_loadPersioneInfo();
        rq_lpi.setCusNumber(MainApp.getInstance().getLoginUser().getCus_number()+"");
        rq_lpi.setPrisonerId(scanStr);
        //发送获取罪犯信息接口请求
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_PRISONER_INFO, rq_lpi, prisonerInfoCallback);
    }

    /**
     * 获取罪犯信息接口回调
     */
    private CustomNetCallBack prisonerInfoCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            Rp_loadPrisonerInfo loadPrisonerInfo = mGson.fromJson(data, Rp_loadPrisonerInfo.class);
            if (loadPrisonerInfo == null) {
                ToastUtils.showLong("罪犯信息为空");
                return;
            }
            tv_prisonerName.setText(loadPrisonerInfo.getPrisoner_name());
            tv_prisonerID.setText(loadPrisonerInfo.getPrisoner_id());
            tv_prisonerDept.setText(loadPrisonerInfo.getDepartment_name());
            mPrisoner = loadPrisonerInfo;

            mLoadingDialog.dismiss();
            if(mHandleBroadcast!=null){
                mHandleBroadcast.overBroadcastReceiver(EduUploadActivity.this);
            }
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取罪犯信息失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取罪犯信息失败");
            LogUtils.e(ex);
        }
    };


    /**
     * 跳转第二页
     */
    private void startToEvaluate() {
//        if (changeLongTime(timer.getText().toString()) < 10000l) {
//            ToastUtils.showLong("谈话时长过短");
//            return;
//        }
        if (mSelectedTalkClassify == null) {
            ToastUtils.showLong("请选择谈话类型");
            return;
        }
        if (mSelectedTalkClassifySon == null) {
            ToastUtils.showLong("请选择谈话类型结果");
            return;
        }
        if(!mSelectedTalkClassify.getDisplay_value().equals(mSelectedTalkClassifySon.getDisplay_value().substring(0,1))){
            ToastUtils.showLong("谈话类型与谈话情况不匹配");
            return;
        }
        Intent it = new Intent(this, EduTalkEvaluateActivity.class);
        Request_Edu_inter inter = new Request_Edu_inter();
        inter.setCusNumber(mPolice.getCus_number() + "");
        inter.setPrisonerId(mPrisoner.getPrisoner_id());
        inter.setPrisonerName(mPrisoner.getPrisoner_name());
        inter.setPoliceId(mPolice.getPolice_id());
        inter.setPoliceName(mPolice.getPolice_name());
        inter.setDepartmentId(mPolice.getDepartment_id() + "");
        inter.setDepartmentName(mPolice.getDepartment_name());
        inter.setTalkTime(TimeUtils.getNowString(new SimpleDateFormat(Constance.DATE_YMDHMS)));
        inter.setTalkTimeLong(String.valueOf(mAudioPlayer.getDurationLocation(getApplicationContext(), mFilePath)));
        inter.setTalkClassify(mSelectedTalkClassify.getDisplay_value());
        inter.setTalkType(mSelectedTalkClassifySon.getDisplay_value());
        //存库相关
        inter.setUp_down("1");
        inter.setFilePath(mFilePath);
        inter.setmTalkClassify(mSelectedTalkClassify.getDisplay_field());
        inter.setmTalkType(mSelectedTalkClassifySon.getDisplay_field());

        it.putExtra(Constance.EDU_UPLUAD_TO_EVALUATE_INTER, inter);
        //以json字符串传递   可以不用序列化
        it.putExtra(Constance.EDU_UPLUAD_TO_EVALUATE_EDUTYPE, mEduTypeArrList);
        startActivity(it);
        finish();
    }


    /**
     * 弹出选择项popwindow
     *
     * @param eduTypes
     * @param showAsDropDownView
     */
    private void showPopWindow(final List<Rp_eduType> eduTypes, final View showAsDropDownView) {
        if (eduTypes == null || eduTypes.size() <= 0) {
            return;
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_custom_list, null);
        //处理popWindow 显示内容
        ListView listView = (ListView) contentView.findViewById(R.id.lv_dialog);
        EduUploadPopAdapter adapter = new EduUploadPopAdapter(this, eduTypes);
        listView.setAdapter(adapter);
        //创建并显示popWindow
        final CustomPopWindow mListPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(showAsDropDownView.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAsDropDown(showAsDropDownView, 0, 0);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mListPopWindow.dissmiss();
                ((TextView) showAsDropDownView).setText(eduTypes.get(position).getDisplay_field());
                switch (showAsDropDownView.getId()) {
                    case R.id.tv_tanhua_leixing://点击谈话类型
                        mSelectedTalkClassify = eduTypes.get(position);
                        mSelectedTalkClassifySon = null;
                        tv_tanhua_content.setText("");
                        break;
                    case R.id.tv_tanhua_content://点击谈话类型子项
                        mSelectedTalkClassifySon = eduTypes.get(position);
                        break;
                }
            }
        });
    }


    /**
     * 开始录音
     */
    private void resolveRecord() {
        if (mPolice == null || mPrisoner == null) {
            ToastUtils.showLong("请先扫码获取信息");
            return;
        }
        mFilePath = FileUtils.getAppPath();
        File file = new File(mFilePath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Toast.makeText(this, "创建文件失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        timer.setVisibility(View.VISIBLE);
        timer.setBase(SystemClock.elapsedRealtime());//计时器清零
        int hour = (int) ((SystemClock.elapsedRealtime() - timer.getBase()) / 1000 / 60);
        timer.setFormat("0" + String.valueOf(hour) + ":%s");
        timer.start();
        //当前民警编号+时间
        //修改文件名称:  民警警号 + 罪犯编号 + UUID.randon()
        mFilePath = FileUtils.getAppPath() + mPolice.getPolice_code() + "_" + mPrisoner.getPrisoner_id() + "_" + UUID.randomUUID().toString() + ".wav";
        LogUtils.e("record path : " + mFilePath);
        mRecorder = new MP3Recorder(new File(mFilePath));

        int size = ScreenUtils.getScreenWidth() / 2;//控件默认的间隔是1
        mRecorder.setDataList(audioWave.getRecList(), size);
        mRecorder.setErrorHandler(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == MP3Recorder.ERROR_TYPE) {
                    ToastUtils.showLong("没有麦克风权限");
                    resolveError();
                }
            }
        });
        try {
            mRecorder.start();
            audioWave.startView();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "录音出现异常", Toast.LENGTH_SHORT).show();
            resolveError();
            return;
        }
        resolveRecordUI();
        mIsRecord = true;
    }

    /**
     * 暂停录音
     */
    private void resolvePause() {
        if (!mIsRecord)
            return;
        if (mRecorder.isPause()) {
            resolveRecordUI();
            mRecorder.setPause(false);
            btn_recordPause.setText("暂停录音");
            timer.setBase(SystemClock.elapsedRealtime() - mTimerNum);
            timer.start();
        } else {
            mRecorder.setPause(true);
            btn_recordPause.setText("继续录音");
            timer.stop();
            String timerNum = timer.getText().toString();
            mTimerNum = changeLongTime(timerNum);
        }
    }

    /**
     * 停止录音
     */
    private void resolveStopRecord() {
        resolveStopUI();
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.setPause(false);
            mRecorder.stop();
            audioWave.stopView();
        }
        mIsRecord = false;
        btn_recordPause.setText("暂停录音");

    }

    /**
     * 重新录音
     */
    private void resolveReRecord() {
        AlertDialog.Builder bd = new AlertDialog.Builder(this);
        AlertDialog ad = bd.create();
        ad.setTitle("提示");
        ad.setMessage("重新录音会删除之前的录音文件？");
        //设置取消选项按钮
        ad.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        //设置确定选项按钮
        ad.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mAudioPlayer.stop();
                MP3Recorder.deleteFile(mFilePath);
                mFilePath = "";
                timer.setBase(SystemClock.elapsedRealtime());//计时器清零
                resolveNormalUI();
            }
        });
        ad.show();
    }

    /**
     * 录音异常
     */
    private void resolveError() {
        resolveNormalUI();
        FileUtils.deleteFile(mFilePath);
        mFilePath = "";
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.stop();
            audioWave.stopView();
        }
    }

    /**
     * 播放录音
     */
    private void resolvePlayRecord() {
        if (StringUtils.isEmpty(mFilePath) || !new File(mFilePath).exists()) {
            Toast.makeText(EduUploadActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        mIsPlay = true;
        mAudioPlayer.playUrl(mFilePath);
        resolvePlayUI();
    }


    /**
     * 暂停播放
     */
    private void resolvePausePlay() {
        mAudioPlayer.playOrPause();
        if (mAudioPlayer.getIsPlaying()) {
            btn_playPause.setText("暂停播放");
        } else {
            btn_playPause.setText("继续播放");
        }
    }

    /**
     * 重置
     */
    private void resolveResetPlay() {
        mFilePath = "";
        if (mIsPlay) {
            mIsPlay = false;
            mAudioPlayer.stop();
        }
        resolveNormalUI();
    }


    /**
     * 播放消息处理
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                    curPosition = (int) msg.obj;
                    break;
                case AudioPlayer.HANDLER_COMPLETE://播放结束
                    mIsPlay = false;
                    resolveStopUI();
                    break;
                case AudioPlayer.HANDLER_PREPARED://播放开始
                    duration = (int) msg.obj;
                    break;
                case AudioPlayer.HANDLER_ERROR://播放错误
                    resolveResetPlay();
                    break;
            }

        }
    };


    @Override
    public void onBackPressed() {
        if (null == mRecorder) {
            this.finish();
            return;
        }
        if (mRecorder.isRecording()) {//录音状态
            AlertDialog.Builder bd = new AlertDialog.Builder(this);
            AlertDialog ad = bd.create();
            ad.setTitle("提示");
            ad.setMessage("退出将会删除本次录音文件，确认退出？");
            //设置取消选项按钮
            ad.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            //设置确定选项按钮
            ad.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    resolveStopRecord();
                    MP3Recorder.deleteFile(mFilePath);
                    timer.stop();
                    EduUploadActivity.this.finish();
                }
            });
            ad.show();
        } else {//非录音状态
            if (!TextUtils.isEmpty(mFilePath)) {//有录音文件
                AlertDialog.Builder bd = new AlertDialog.Builder(this);
                AlertDialog ad = bd.create();
                ad.setTitle("提示");
                ad.setMessage("退出将会删除本次录音文件，确认退出？");
                //设置取消选项按钮
                ad.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                //设置确定选项按钮
                ad.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mAudioPlayer.stop();
                        MP3Recorder.deleteFile(mFilePath);
                        EduUploadActivity.this.finish();
                    }
                });
                ad.show();
            } else {//没有录音文件
                EduUploadActivity.this.finish();
            }
        }
    }

    /**
     * 开始录音
     */
    private void resolveRecordUI() {
        btn_recordPause.setVisibility(View.VISIBLE);
        btn_recordStop.setVisibility(View.VISIBLE);
        btn_play.setVisibility(View.GONE);
        btn_startRecord.setVisibility(View.GONE);
        btn_playPause.setVisibility(View.GONE);
        btn_playStop.setVisibility(View.GONE);
        btn_ReRecord.setVisibility(View.GONE);
        btn_submit.setVisibility(View.GONE);
    }

    /**
     * 重置
     */
    private void resolveNormalUI() {
        btn_startRecord.setVisibility(View.VISIBLE);
        btn_play.setVisibility(View.GONE);
        btn_recordStop.setVisibility(View.GONE);
        btn_recordPause.setVisibility(View.GONE);
        btn_playPause.setVisibility(View.GONE);
        btn_playStop.setVisibility(View.GONE);
        btn_ReRecord.setVisibility(View.GONE);
        btn_submit.setVisibility(View.GONE);
        btn_recordPause.setText("暂停录音");
        btn_playPause.setText("暂停播放");
    }

    /**
     * 停止录音
     */
    private void resolveStopUI() {
        btn_play.setVisibility(View.VISIBLE);
        btn_ReRecord.setVisibility(View.VISIBLE);
        btn_submit.setVisibility(View.VISIBLE);
        btn_recordPause.setVisibility(View.GONE);
        btn_recordStop.setVisibility(View.GONE);
        btn_startRecord.setVisibility(View.GONE);
        btn_playPause.setVisibility(View.GONE);
        btn_playStop.setVisibility(View.GONE);
        btn_playPause.setText("暂停播放");
    }

    /**
     * 开始播放
     */
    private void resolvePlayUI() {
        btn_playPause.setVisibility(View.VISIBLE);
        btn_playStop.setVisibility(View.VISIBLE);
        btn_ReRecord.setVisibility(View.VISIBLE);
        btn_submit.setVisibility(View.VISIBLE);
        btn_startRecord.setVisibility(View.GONE);
        btn_play.setVisibility(View.GONE);
        btn_recordStop.setVisibility(View.GONE);
        btn_recordPause.setVisibility(View.GONE);
        btn_playPause.setText("暂停播放");
    }

    /**
     * "HH:mm:ss"的String类型转化为毫秒数
     *
     * @param strTime
     * @return
     */
    private long changeLongTime(String strTime) {
        long time = 0l;
        try {
            String[] splitTime = strTime.split(":");
            int hour = Integer.parseInt(splitTime[0]);
            int min = Integer.parseInt(splitTime[1]);
            int sec = Integer.parseInt(splitTime[2]);
            time = (((hour * 60 + min) * 60) + sec) * 1000l;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }

    @Override
    protected void onDestroy() {
        if(mAudioPlayer!=null){
            mAudioPlayer.stop();
        }
        if(mHandleBroadcast!=null){
            try {
                mHandleBroadcast.overBroadcastReceiver(this);
            }catch (Exception e){
            }
        }
        super.onDestroy();
    }
}
